package com.sunfeng.netty.atguigu.protocoltcp2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author 孙峰
 * @Description: TODO
 * @date 2020/12/11 10:27
 */
public class MyClientHandler extends SimpleChannelInboundHandler<UserProtocol> {
    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            String mes = "我是中国人！！";
            byte[] content = mes.getBytes(StandardCharsets.UTF_8);
            int length = mes.getBytes(StandardCharsets.UTF_8).length;
            // 创建协议包对象
            UserProtocol userProtocol = new UserProtocol();
            userProtocol.setContent(content);
            userProtocol.setLength(length);
            ctx.writeAndFlush(userProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, UserProtocol msg) throws Exception {
        byte[] content = msg.getContent();
        int length = msg.getLength();
        System.out.println("客户端收到消息");
        System.out.println("数据长度为:" + length);
        System.out.println("数据内容为:" + new String(content, StandardCharsets.UTF_8));
        System.out.println("接受数据的次数：" + (++count));
    }
}
